package com.yangjun.service.bussiness;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yangjun.common.DVConstants;
import com.yangjun.dao.mybatis.mapper.businessAnalysis.SemConversionMapper;
import com.yangjun.entity.businessAnalysis.SemConversionEntity;
import com.yangjun.entity.common.CompareEntity;

@Service
public class SemConversionService {
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
 	@Autowired
    private SemConversionMapper semConversionMapper;
 	public Map<String,String> querySiteId(){
 		Map<String,String> resultMap = Maps.newHashMap();
 		resultMap.put("SEM","");
 		resultMap.put("PC","1");
 		resultMap.put("WAP","10");
 		return resultMap;
 	}
 	
 	public Map<String,SemConversionEntity> querySiteDayFlow(String siteid,String contrastDate){
 		Map<String,SemConversionEntity> resultMap = Maps.newHashMap();
 		String[] dateArr = new String[3];
 		try {
	 		Calendar cal=Calendar.getInstance();
	 		dateArr[0]=sdf.format(cal.getTime());
	 		cal.add(Calendar.DATE,-1);
	 		dateArr[1]=sdf.format(cal.getTime());
	 		if(StringUtils.isEmpty(contrastDate)){
	 			dateArr[2]=dateArr[1];
	 		}else{
				cal.setTime(sdf.parse(contrastDate));
	 			dateArr[2]=sdf.format(cal.getTime());
	 		}
 		} catch (ParseException e) {
			e.printStackTrace();
		}
 		List<SemConversionEntity> entityList = semConversionMapper.querySiteDayFlow(dateArr,siteid);
 		Map<String,SemConversionEntity> dateEntityMap = Maps.newHashMap();
 		for(SemConversionEntity entity  : entityList){
 			dateEntityMap.put(entity.getDateDay(), entity);
 		}
		resultMap.put("today", dateEntityMap.get(dateArr[0]));
		resultMap.put("yesterday", dateEntityMap.get(dateArr[1]));
		resultMap.put("contrastDay", dateEntityMap.get(dateArr[2]));
 		return resultMap;
 	}

	public Map<String,Object> querySiteHourFlow(String siteid,String currentDate,String contrastDate){
		//一次性查询两天的数据
		List<SemConversionEntity> LineChartList = semConversionMapper.querySiteChannelSourceKeywordHourFlow(siteid,null,null,new String[]{currentDate, contrastDate});
		return queryLineChartData(DVConstants.HOUR_ARR,LineChartList,new String[]{currentDate,contrastDate},DVConstants.COMPARISON_LEGEND);
	}
	public Map<String,Object> querySiteHourActionNetamt(String siteid,String action,String currentDate,String contrastDate){
		//一次性查询两天的数据
		List<SemConversionEntity> entityList = semConversionMapper.querySiteHourActionNetamt(siteid,action, new String[]{currentDate, contrastDate});
		return queryLineChartData(DVConstants.HOUR_ARR,entityList,new String[]{currentDate,contrastDate},DVConstants.COMPARISON_LEGEND);
	}
	
	public Map<String,Object> queryChannelTable(String siteid,String date,String dimension,String orderBy){
		DecimalFormat decimalFormat=new DecimalFormat("0.0000");
		Map<String,Object> resultMap = Maps.newHashMap();
		String orderSql = null;
		if(StringUtils.isNotEmpty(dimension)){
				orderSql = " order by ";
			if("来访次数".equals(dimension)){
				orderSql+="visitTimes ";
			}else if("访客数".equals(dimension)){
				orderSql+="visitors ";
			}else if("跳出率".equals(dimension)){
				orderSql+="jumpRate ";
			}else if("访问深度".equals(dimension)){
				orderSql="avgDepth ";
			}else if("访问时长".equals(dimension)){
				orderSql+="avgVisitlength ";
			}else if("销售额".equals(dimension)){
				orderSql+="netamt ";
			}else if("订单数".equals(dimension)){
				orderSql+="orders ";
			}else if("新单订单数".equals(dimension)){
				orderSql+="newOrders ";
			}else if("新单销售额".equals(dimension)){
				orderSql+="newNetamt ";
			}
			orderSql+=orderBy;
		}else{
			orderSql=" order by visitTimes desc";
		}
		
		List<SemConversionEntity> entityList = semConversionMapper.queryChannelTable(siteid,date,orderSql);
		List<String[]> detailList = Lists.newArrayList();
		String[] detailListTitle = new String[]{"来源渠道","来源次数","访客数","跳出率","访问时长","订单数","销售额","新单订单数","新单销售额"};
		int visitTimesSum = 0;
		int netamtSum = 0;
		int ordersSum = 0;
		int newOrdersNetamtSum = 0;
		
		String[] proportionTitle = new String[]{"占比","百度PC","360PC","搜狗PC","UC无线","百度WAP","360WAP","搜狗WAP","其他"};
		String[] proportionDimension = new String[]{"来访次数占比","销售额占比","订单量占比","新单销售额占比"};
		


		for(SemConversionEntity entity : entityList){
			String[] itemArr = new String[9];
			itemArr[0]=entity.getChannel();
			
			visitTimesSum+=entity.getVisitTimes();
			itemArr[1]=entity.getVisitTimes().toString();
			
			itemArr[2]=entity.getVisitors().toString();
			itemArr[3]=entity.getJumpRate().toString();
			itemArr[4]=entity.getAvgVisitlength().toString();
			
			ordersSum+=entity.getOrders();
			itemArr[5]=entity.getOrders().toString();
			
			netamtSum+=entity.getNetamt();
			itemArr[6]=entity.getNetamt().toString();
			
			itemArr[7]=entity.getNewOrders().toString();
			
			newOrdersNetamtSum+=entity.getNewNetamt();
			itemArr[8]=entity.getNewNetamt().toString();
			
			detailList.add(itemArr);
		}
		Map<String,Map<String,String>> channelMap = Maps.newHashMap();
		for(SemConversionEntity entity  : entityList){
			String channel = entity.getChannel();
			Map<String,String> itemMap = Maps.newHashMap();
			itemMap.put("来访次数占比", entity.getVisitTimes()==0?"0":decimalFormat.format(entity.getVisitTimes()/Float.valueOf(visitTimesSum)));
			itemMap.put("销售额占比", entity.getNetamt()==0?"0":decimalFormat.format(entity.getNetamt()/Float.valueOf(netamtSum)));
			itemMap.put("订单量占比",entity.getOrders()==0?"0":decimalFormat.format(entity.getOrders()/Float.valueOf(ordersSum)));
			itemMap.put("新单销售额占比",entity.getNewNetamt()==0?"0":decimalFormat.format(entity.getNewNetamt()/Float.valueOf(newOrdersNetamtSum)));
			channelMap.put(channel, itemMap);
		}
		Object[][] proportionArray = new Object[proportionDimension.length][proportionTitle.length];
		for(int i=0,len=proportionDimension.length;i<len;i++){
			for(int j=0,colLen=proportionTitle.length;j<colLen;j++){
				if(j==0){
					proportionArray[i][j]=proportionDimension[i];
					continue;
				}
				Map<String,String> dimensionMap = channelMap.get(proportionTitle[j]);
				if(dimensionMap!=null){
					proportionArray[i][j]= dimensionMap.get(proportionArray[i][0].toString());
				}else{
					proportionArray[i][j]="0";
				}
			}
		}
		resultMap.put("proportion", proportionArray);
		resultMap.put("detail", detailList);
		return resultMap;
	}
	
	public Map<String,Object> querySiteChannelHourFlow(String siteid,String channel,String currentDate,String contrastDate){
		//一次性查询两天的数据
		List<SemConversionEntity> entityList = semConversionMapper.querySiteChannelSourceKeywordHourFlow(siteid,channel,null,new String[]{currentDate, contrastDate});
		return queryLineChartData(DVConstants.HOUR_ARR,entityList,new String[]{currentDate,contrastDate},DVConstants.COMPARISON_LEGEND);
	}
	
	public List<String[]> querySourceKeywordTable(String siteid,String date,String channel,String dimension,String orderBy){
		List<String[]> resultList = Lists.newArrayList();
		String orderSql = null;
		if(StringUtils.isNotEmpty(dimension)){
			orderSql = " order by ";
			if("来访次数".equals(dimension)){
				orderSql+=" visitTimes ";
			}else if("访客数".equals(dimension)){
				orderSql+=" visitors ";
			}else if("跳出率".equals(dimension)){
				orderSql+=" jumpRate ";
			}else if("访问深度".equals(dimension)){
				orderSql+=" avgDepth ";
			}else if("销售额".equals(dimension)){
				orderSql+=" netamt ";
			}else if("订单数".equals(dimension)){
				orderSql+=" orders ";
			}
			orderSql+=" "+orderBy;
		}else{
			orderSql=" order by visitTimes desc";
		}
		List<SemConversionEntity> entityList = semConversionMapper.querySourceKeywordTable(siteid, date,channel,orderSql);
		if(entityList.size()>0){
			for(SemConversionEntity entity : entityList){
				String[] itemArr = new String[7];
				itemArr[0]=entity.getSourceKeyword();
				itemArr[1]=entity.getVisitTimes().toString();
				itemArr[2]=entity.getVisitors().toString();
				itemArr[3]=entity.getJumpRate().toString();
				itemArr[4]=entity.getAvgDepth().toString();
				itemArr[5]=entity.getOrders().toString();
				itemArr[6]=entity.getNetamt().toString();
				resultList.add(itemArr);

			}
		}
		return resultList;
	}
	public List<String[]> queryChannelSourceKeywordTable(String siteid,String date,String channel,String sourceKeyword){
		List<String[]> resultList = Lists.newArrayList();
		List<SemConversionEntity> entityList = semConversionMapper.queryChannelSourceKeywordTable(siteid, date,channel,sourceKeyword);
		if(entityList.size()>0){
			for(SemConversionEntity entity : entityList){
				String[] itemArr = new String[5];
				itemArr[0]=entity.getChannel();
				itemArr[1]=entity.getVisitTimes().toString();
				itemArr[2]=entity.getVisitors().toString();
				itemArr[3]=entity.getOrders().toString();
				itemArr[4]=entity.getNetamt().toString();
				resultList.add(itemArr);
			}
		}
		return resultList;
	}
	public Map<String,Object> querySiteChannelSourceKeywordHourFlow(String siteid,String channel,String sourceKeyword,String currentDate,String contrastDate){
		//一次性查询两天的数据
		List<SemConversionEntity> entityList = semConversionMapper.querySiteChannelSourceKeywordHourFlow(siteid,channel,sourceKeyword,new String[]{currentDate, contrastDate});
		return queryLineChartData(DVConstants.HOUR_ARR,entityList,new String[]{currentDate,contrastDate},DVConstants.COMPARISON_LEGEND);
	}
	private Map<String,Object> queryLineChartData(String[] xAxisArr,
			List<SemConversionEntity> entityList,String[] dateArr,String[] nameArr){
		//用来返回结果的结果集
		Map<String,Object> resultMap = Maps.newHashMap();
		//用来存放一天每个小时的数据（或其他时间维度）
		Map<String,SemConversionEntity> entityMap = null;
		//用来组装每天每个小时的数据（或其他时间维度）
		Map<String,Map<String,SemConversionEntity>> dateMap = Maps.newHashMap();
		//用来存放返回的对象名
		Map<String,String> nameMap = Maps.newHashMap();
		Map<String,String> dimensionMap = Maps.newHashMap();
		
		dimensionMap.put("visitTimes", "来访次数");
		dimensionMap.put("visitors", "访客数");
		dimensionMap.put("newVisitors", "新访客数");
		dimensionMap.put("jumpRate", "跳出率");
		dimensionMap.put("netamt", "销售额");
		dimensionMap.put("orders", "订单数");
		dimensionMap.put("newOrders", "新单订单数");
		dimensionMap.put("newNetamt", "新单销售额");
		dimensionMap.put("tq", "TQ");
		dimensionMap.put("demand", "需求登记");
		dimensionMap.put("addToCard", "购物车");
		dimensionMap.put("faxCallBack", "电话回拨");
		if(entityList.size()>0){
			//遍历集合提取时间作为key，实体作为value,封装不同日期的Map集合
			for(SemConversionEntity entity : entityList){
				for(int i=0,len=dateArr.length;i<len;i++){
					//存放返回的对象名
					nameMap.put(dateArr[i], nameArr[i]);
					if(entity.getDateDay().equals(dateArr[i])){
						entityMap = dateMap.get(entity.getDateDay());
						if(entityMap==null){
							entityMap = Maps.newHashMap();
						}
						entityMap.put(entity.getHour(), entity);
						dateMap.put(entity.getDateDay(), entityMap);
					}
				}
			}
			Map<String,CompareEntity> resultDataMap = Maps.newHashMap();
			//遍历当前日期以及对比日期
			for(Map.Entry<String,Map<String,SemConversionEntity>> entryDateMap: dateMap.entrySet()){
				
				String date = nameMap.get(entryDateMap.getKey());
				Map<String,SemConversionEntity> itemMap= entryDateMap.getValue();
				
				String[] visitTimesArr = new String[xAxisArr.length];
				String[] visitorsArr = new String[xAxisArr.length];
				String[] newVisitorsArr = new String[xAxisArr.length];
				String[] jumpRateArr = new String[xAxisArr.length];
				String[] netamtArr = new String[xAxisArr.length];
				String[] ordersArr = new String[xAxisArr.length];
				String[] newOrdersArr = new String[xAxisArr.length];
				String[] newNetamtArr = new String[xAxisArr.length];
				String[] tqArr = new String[xAxisArr.length];
				String[] demandArr = new String[xAxisArr.length];
				String[] addToCardArr = new String[xAxisArr.length];
				String[] faxCallBackArr = new String[xAxisArr.length];
				String[] allActionArr = new String[xAxisArr.length];

				//遍历时间数组获取对应的时间实体，空数据给默认值
				for(int i=0,len=xAxisArr.length;i<len;i++ ){
					visitTimesArr[i]=visitorsArr[i]=newVisitorsArr[i]=jumpRateArr[i]=netamtArr[i]=ordersArr[i]=
							newOrdersArr[i]=newNetamtArr[i]=tqArr[i]=demandArr[i]=addToCardArr[i]=faxCallBackArr[i]=allActionArr[i]="0";
					SemConversionEntity hourEntity = itemMap.get(xAxisArr[i]);
					if(hourEntity!=null){
						visitTimesArr[i]  = String.valueOf(hourEntity.getVisitTimes());
						visitorsArr[i]  = String.valueOf(hourEntity.getVisitors());
						newVisitorsArr[i]  = String.valueOf(hourEntity.getNewVisitors());
						jumpRateArr[i] = String.valueOf(hourEntity.getJumpRate());
						netamtArr[i]  = String.valueOf(hourEntity.getNetamt());
						ordersArr[i]  = String.valueOf(hourEntity.getOrders());
						newOrdersArr[i]  = String.valueOf(hourEntity.getNewOrders());
						newNetamtArr[i]  = String.valueOf(hourEntity.getNetamt());
						tqArr[i]  = String.valueOf(hourEntity.getTqTimes());
						demandArr[i]  = String.valueOf(hourEntity.getDemandTimes());
						addToCardArr[i]  = String.valueOf(hourEntity.getAddToCardTimes());
						faxCallBackArr[i]  = String.valueOf(hourEntity.getFaxCallBackTimes());
						allActionArr[i] = String.valueOf(hourEntity.getTqTimes()+hourEntity.getDemandTimes()+hourEntity.getAddToCardTimes()+hourEntity.getFaxCallBackTimes());
					}
				}
					addItemToResultMap(date,dimensionMap.get("visitTimes"),"visitTimes",visitTimesArr,resultDataMap);
					addItemToResultMap(date,dimensionMap.get("visitors"),"visitors",visitorsArr,resultDataMap);
					addItemToResultMap(date,dimensionMap.get("newVisitors"),"newVisitors",newVisitorsArr,resultDataMap);
					addItemToResultMap(date,dimensionMap.get("jumpRate"),"jumpRate",jumpRateArr,resultDataMap);
					addItemToResultMap(date,dimensionMap.get("netamt"),"netamt",netamtArr,resultDataMap);
					addItemToResultMap(date,dimensionMap.get("orders"),"orders",ordersArr,resultDataMap);
					addItemToResultMap(date,dimensionMap.get("newOrders"),"newOrders",newOrdersArr,resultDataMap);
					addItemToResultMap(date,dimensionMap.get("newNetamt"),"newNetamt",newNetamtArr,resultDataMap);
					
					addItemToResultMap(date,dimensionMap.get("tq"),"tq",tqArr,resultDataMap);
					addItemToResultMap(date,dimensionMap.get("demand"),"demand",demandArr,resultDataMap);
					addItemToResultMap(date,dimensionMap.get("addToCard"),"addToCard",addToCardArr,resultDataMap);
					addItemToResultMap(date,dimensionMap.get("faxCallBack"),"faxCallBack",faxCallBackArr,resultDataMap);
					addItemToResultMap(date,"全部","allAction",allActionArr,resultDataMap);
			}
			resultMap.putAll(resultDataMap);
		}else{
			for(Map.Entry<String,String> entry : dimensionMap.entrySet()){
				CompareEntity compareEntity = new CompareEntity();
				compareEntity.setContrastDataArr(new String[]{});
				compareEntity.setCurrentDataArr(new String[]{});
				compareEntity.setName(entry.getValue());
				resultMap.put(entry.getKey(), compareEntity);
			}
		}
		//构建不同维度的数组
		resultMap.put("xAxis",xAxisArr);
		resultMap.put("legendName",dateArr);
		return resultMap;
	}
	/**
	 * @Description 组装折线图数据
	 * @param date
	 * @param legendName
	 * @param deminsionName
	 * @param itemArr
	 * @param resultDataMap
	 * @return
	 * @author yangjun
	 * @Date 2017年3月10日 下午2:40:42
	 */
	private Map<String,CompareEntity> addItemToResultMap(String date,String legendName,String deminsionName,String[] itemArr,Map<String,CompareEntity> resultDataMap){
		CompareEntity compareEntity = resultDataMap.get(deminsionName);
		if(compareEntity==null){
			compareEntity = new CompareEntity();
			compareEntity.setName(legendName);
		}
		if("currentData".equals(date)){
			Calendar c = Calendar.getInstance();
			//获取当前小时，截取当天该小时之前的数据返回到前台
			compareEntity.setCurrentDataArr(Arrays.copyOfRange(itemArr,0,c.get(Calendar.HOUR_OF_DAY)+1));
		}else if("contrastData".equals(date)){
			compareEntity.setContrastDataArr(itemArr);
		}
		resultDataMap.put(deminsionName, compareEntity);
		return resultDataMap;
	}
	
	public Map<String,Object> queryHourAndProvincePie(String siteid,String date){
		List<SemConversionEntity> provinceList = semConversionMapper.queryProvincePie(siteid, date);
		List<SemConversionEntity> hourList = semConversionMapper.queryHourPie(siteid, date);
		Map<String,Object> resultMap = Maps.newHashMap();
		handlePieResult(resultMap,handlePieItem(provinceList,"province","来访次数"),handlePieItem(hourList,"hour","来访次数"),"visitTimes");
		handlePieResult(resultMap,handlePieItem(provinceList,"province","访客数"),handlePieItem(hourList,"hour","访客数"),"visitors");
		handlePieResult(resultMap,handlePieItem(provinceList,"province","订单数"),handlePieItem(hourList,"hour","订单数"),"orders");
		handlePieResult(resultMap,handlePieItem(provinceList,"province","销售额"),handlePieItem(hourList,"hour","销售额"),"netamt");
		return resultMap;
	}
	private Map<String,Object> handlePieResult(Map<String,Object> resultMap,Map<String,Object> provinceItem,Map<String,Object> hourItem,String dimension){
		Map<String,Object> dimensiontMap = Maps.newHashMap();
		dimensiontMap.put("province", provinceItem);
		dimensiontMap.put("hour", hourItem);
		resultMap.put(dimension, dimensiontMap);
		return resultMap;
	}
	private Map<String,Object> handlePieItem(List<SemConversionEntity>  entityList,String target,String dimension){
		Map<String,Object> resultMap = Maps.newHashMap();
		List<Map<String,String>> itemList = Lists.newArrayList();
		resultMap.put("name",dimension);
		for(SemConversionEntity entity : entityList){
			Map<String,String> itemMap = Maps.newHashMap();
			int value=0;
			if("来访次数".equals(dimension)){
				value=entity.getVisitTimes();
			}else if("访客数".equals(dimension)){
				value=entity.getVisitors();
			}else if("订单数".equals(dimension)){
				value=entity.getOrders();
			}else if("销售额".equals(dimension)){
				value=entity.getNetamt();
			}
			if(value==0){
				continue;
			}
			itemMap.put("value",String.valueOf(value));
			String name = null;
			if("province".equals(target)){
				name = entity.getProvince();
			}else if("hour".equals(target)){
				name = Integer.valueOf(entity.getHour())+"点";
			}
			itemMap.put("name", name);
			itemList.add(itemMap);
		}
		Collections.sort(itemList, new Comparator<Map<String,String>>() {
			@Override
			public int compare(Map<String, String> m1, Map<String, String> m2) {
				int value1 = Integer.valueOf(m1.get("value"));
				int value2 = Integer.valueOf(m2.get("value"));
				if(value1<value2){
					return 1;
				}else{
					return -1;
				}
			}
		});
		if(itemList.size()>10){
			List<Map<String,String>> otherList = itemList.subList(10,itemList.size());
			Map<String,String> otherMap = Maps.newHashMap();
			int sum=0;
			for(Map<String,String> map : otherList){
				sum+=Integer.valueOf(map.get("value"));
			}
			otherMap.put("name","其他");
			otherMap.put("value",String.valueOf(sum));
			itemList = itemList.subList(0, 10);
			itemList.add(otherMap);
		}
		resultMap.put("data",itemList);
		List<String> lengendList = Lists.newArrayList();
		for(Map<String,String> itemMap : itemList){
			if(Integer.valueOf(itemMap.get("value"))>0){
				lengendList.add(itemMap.get("name").toString());
			}
		}
		resultMap.put("legend",lengendList);
		return resultMap;
	}
	
	public List<String[]> queryHotSalesWares(String siteid,String date,String channel,String dimension,String orderBy){
		String orderSql = null;
		if(StringUtils.isNotEmpty(dimension)){
			orderSql = " order by ";
			if("销售数量".equals(dimension)){
				orderSql+=" qty ";
			}else if("销售额".equals(dimension)){
				orderSql+=" netamt ";
			}
			orderSql+=" "+orderBy;
		}else{
			orderSql=" order by qty desc";
		}
		
		List<String[]> resultList = Lists.newArrayList();
		List<SemConversionEntity> entityList = semConversionMapper.queryHotSalesWares(siteid,date,channel,orderSql);
		if(entityList.size()>0){
			for(SemConversionEntity entity : entityList){
				String[] itemArr = new String[4];
				itemArr[0]=entity.getWareCode();
				itemArr[1]=entity.getWareName();
				itemArr[2]=entity.getQty().toString();
				itemArr[3]=entity.getNetamt().toString();
				resultList.add(itemArr);
			}
		}
		return resultList;
	}
}
